﻿using FreeSql;
using Microsoft.Extensions.DependencyInjection;

namespace Msung.Core.Freesql
{
    public static class AddMultiNoSqlDBSetup
    {

        public static void AddMultiNoSqlDB(this IServiceCollection services)
        {
            var fsql = new FreeSqlCloud<string>(); //提示：泛型可以传入 string
            List<MultiNoSqlDb> dbsList = AppSetting.MultiNoSqlDbs;
            if (dbsList.Any())
            {
                foreach (var dbObj in dbsList)
                {
                    fsql.Register(dbObj.Name, () =>
                    new FreeSqlBuilder()
                    .UseNoneCommandParameter(true)
                    .UseConnectionString(dbObj.DbType, dbObj.ConnectionString)
                    .UseQuestDbRestAPI(dbObj.Api, dbObj.UserName, dbObj.Password)
                    .Build());
                    fsql.Aop.CurdAfter += (s, e) =>
                    {
                        Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}: " + $"{e.EntityType.FullName} " + $"{e.ElapsedMilliseconds}ms, " + $"{e.Sql}");
                    };
                    fsql.Aop.CurdBefore += (s, e) =>
                    {

                    };
                }
            }
            fsql.DistributeTrace = log => Console.WriteLine(log.Split('\n')[0].Trim());

            services.AddSingleton<IFreeSql>(fsql);
            services.AddSingleton(fsql);
        }
    }
}
